package com.ncmmall.application.securitys.page;

import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.ncmmall.domain.security.page.Page;
import com.ncmmall.domain.security.page.PageRepository;
import com.ncmmall.domain.security.page.Permission;
import com.ncmmall.domain.security.page.PermissionRepository;
import com.ncmmall.domain.security.page.QPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author linxs
 *         页面管理
 */
@Service
public class PageApplication {

    @Autowired
    private PageRepository pageRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 添加页面
     *
     * @param page
     * @return
     */
    public Page create(Page page) {

        pageRepository.save(page);

        List<String> permissions = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(page.getPermissionData());
        for (String item : permissions) {
            String name = item.substring(0, item.indexOf(":"));
            String value = item.substring(item.indexOf(":") + 1, item.length());
            Permission permission = new Permission();
            permission.setName(name);
            permission.setPermission(value);
            permission.setPage(page);
            permissionRepository.save(permission);
        }

        return page;
    }

    /**
     * 修改页面信息
     *
     * @param page
     * @return
     */
    public Page modify(Page page) {

        Page old = queryChannelService.findOne(QPage.page.id.eq(page.getId()), Page.class);
        old.setName(page.getName());
        old.setHref(page.getHref());

        pageRepository.save(old);

        permissionRepository.delete(old.getPermissions());
        List<String> permissions = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(page.getPermissionData());
        for (String item : permissions) {
            String name = item.substring(0, item.indexOf(":"));
            String value = item.substring(item.indexOf(":") + 1, item.length());
            Permission permission = new Permission();
            permission.setName(name);
            permission.setPermission(value);
            permission.setPage(old);
            permissionRepository.save(permission);
        }

        return old;
    }

    /**
     * 删除页面
     *
     * @param page
     */
    public void remove(Page page) {
        permissionRepository.delete(page.getPermissions());
        page.setPermissions(null);
        pageRepository.delete(page);
    }

}
